package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.PageResult;
import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.dto.PayOrderRequest;
import cn.edu.ncut.cs.springboot.petmanagementsystem.dto.RefundRequest;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Order;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.OrderService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.UserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/order")
@Tag(name = "订单模块")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Operation(summary = "提交订单并生成支付信息")
    @PostMapping("/create")
    public Result<Order> createOrder(@RequestBody CreateOrderRequest request) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            Order order = orderService.createOrder(
                    user.getId(),
                    request.getCartIds(),
                    request.getShippingAddress(),
                    request.getReceiverName(),
                    request.getReceiverPhone()
            );
            return Result.success("订单创建成功", order);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return Result.error("创建订单失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查询当前用户的订单记录")
    @GetMapping("/list")
    public PageResult<Order> getOrderList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return PageResult.pageError("用户不存在");
            }

            IPage<Order> page = orderService.getOrderList(user.getId(), pageNum, pageSize);
            return PageResult.success(page);
        } catch (Exception e) {
            log.error("查询订单列表失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查看订单详细信息")
    @GetMapping("/detail/{id}")
    public Result<Order> getOrderDetail(
            @Parameter(description = "订单ID") @PathVariable Long id) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            Order order = orderService.getOrderDetail(id, user.getId());
            if (order != null) {
                return Result.success(order);
            }
            return Result.error("订单不存在");
        } catch (Exception e) {
            log.error("查询订单详情失败", e);
            return Result.error("查询失败");
        }
    }

    @Operation(summary = "更新订单状态（支付、发货、完成）")
    @PutMapping("/status/{id}")
    public Result<?> updateOrderStatus(
            @Parameter(description = "订单ID") @PathVariable Long id,
            @Parameter(description = "订单状态") @RequestParam Integer status) {
        try {
            boolean success = orderService.updateOrderStatus(id, status);
            return success ? Result.success("更新成功") : Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新订单状态失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    @Operation(summary = "取消订单")
    @PutMapping("/cancel/{id}")
    public Result<?> cancelOrder(@Parameter(description = "订单ID") @PathVariable Long id) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = orderService.cancelOrder(id, user.getId());
            return success ? Result.success("订单取消成功") : Result.error("订单取消失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return Result.error("取消订单失败: " + e.getMessage());
        }
    }

    @Operation(summary = "确认收货")
    @PutMapping("/confirm/{id}")
    public Result<?> confirmOrder(@Parameter(description = "订单ID") @PathVariable Long id) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = orderService.confirmOrder(id, user.getId());
            return success ? Result.success("确认收货成功") : Result.error("确认收货失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("确认收货失败", e);
            return Result.error("确认收货失败: " + e.getMessage());
        }
    }

    @Operation(summary = "订单支付")
    @PostMapping("/pay/{id}")
    public Result<?> payOrder(
            @Parameter(description = "订单ID") @PathVariable Long id,
            @RequestBody PayOrderRequest request) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            if (request.getPaymentMethod() == null) {
                return Result.error("请选择支付方式");
            }

            boolean success = orderService.payOrder(id, user.getId(), request.getPaymentMethod());
            return success ? Result.success("支付成功") : Result.error("支付失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("订单支付失败", e);
            return Result.error("支付失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查询订单状态")
    @GetMapping("/status/{id}")
    public Result<Integer> getOrderStatus(@Parameter(description = "订单ID") @PathVariable Long id) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            Integer status = orderService.getOrderStatus(id, user.getId());
            if (status != null) {
                return Result.success("查询成功", status);
            }
            return Result.error("订单不存在");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("查询订单状态失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "申请退款")
    @PostMapping("/refund/{id}")
    public Result<?> refundOrder(
            @Parameter(description = "订单ID") @PathVariable Long id,
            @RequestBody RefundRequest request) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = orderService.refundOrder(id, user.getId(), request.getReason());
            return success ? Result.success("退款申请提交成功") : Result.error("退款申请失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("申请退款失败", e);
            return Result.error("退款申请失败: " + e.getMessage());
        }
    }

    @Data
    public static class CreateOrderRequest {
        private List<Long> cartIds;
        private String shippingAddress;
        private String receiverName;
        private String receiverPhone;
    }
}
